package com.dw.etl.core.springbatch.job;

import com.dw.etl.core.db.DynamicDataSource;
import com.dw.etl.core.db.ThreadLocalDataSource;
import com.dw.etl.core.springbatch.writer.InsertWriter;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.ColumnMapRowMapper;
import org.springframework.transaction.PlatformTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Map;

/**
 * Created by liujunlei on 2021/5/20.
 */
@Configuration
public class HosToOdsJob {

    @Resource
    private JobBuilderFactory jobBuilderFactory;    //用于构建JOB

    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    PlatformTransactionManager transactionManager;



    @Bean
    public Job simpleJob(){
        return jobBuilderFactory.get("simpleJob")
                .incrementer(new RunIdIncrementer()) //防止重复的
                .start(simpleStep(null))//为Job指定Step
                .build();
    }

    @Bean
    public Step simpleStep(InsertWriter insertWriter) {
        return this.stepBuilderFactory.get("sampleStep")
                .transactionManager(transactionManager)
                .<Map<String,Object>, Map<String,Object>>chunk(1000)
                .reader(simpleReader(null,null))
                .writer(insertWriter)
                .build();
    }

    @Bean(name = "simpleReader")
    @StepScope
    public JdbcCursorItemReader<Map<String,Object>> simpleReader(@Value("#{jobParameters[qSql]}") String qSql,@Value("#{jobParameters[idDbSou]}") String idDbSou) {
        ThreadLocalDataSource.setLocalSource(idDbSou);
        return new JdbcCursorItemReaderBuilder<Map<String,Object>>()
                .dataSource((DataSource) DynamicDataSource.dataSourceMap.get(idDbSou))
                .name("simpleReader")
                .sql(qSql)
                .rowMapper(new ColumnMapRowMapper())
                .build();
    }

}
